package com.ycy.servlet;

import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.servlet.auth.oauth2.AbstractAuthorizationCodeCallbackServlet;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.services.plus.Plus;
import com.google.api.services.plus.PlusRequest;
import com.google.api.services.plus.model.Activity;
import com.google.api.services.plus.model.ActivityFeed;
import com.ycy.ss.Constant;
import com.ycy.ss.status.AllStatus;
import com.ycy.ss.status.StatusGoogle;
import com.ycy.util.GoogleUtil;

/**
 * A servlet which handles the OAuth 2.0 authentication result and retrieves an access token on successful
 * authentication.
 * 
 * @author Jennifer Murphy
 * @author Lee Denison
 */
public class GoogleConsumer extends AbstractAuthorizationCodeCallbackServlet{

	private static final long serialVersionUID = 1L;

	private static final Logger log = Logger.getLogger(GoogleConsumer.class);

	@Override
	protected void onSuccess(HttpServletRequest request, HttpServletResponse response, Credential credential)
			throws ServletException, IOException{

		StatusGoogle statusGoogle = new StatusGoogle();

		Plus.Builder builder = new Plus.Builder(GoogleUtil.TRANSPORT, GoogleUtil.JSON_FACTORY, null);
		Plus unauthenticatedPlus = builder.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer(){
			public void initialize(JsonHttpRequest jsonHttpRequest) throws IOException{
				PlusRequest plusRequest = (PlusRequest) jsonHttpRequest;
				plusRequest.setKey(Constant.getAccountInfo("google.google_api_key"));
			}
		}).build();
//		statusGoogle.UNAUTHENTICATED_PLUS = unauthenticatedPlus;

		// Credential credential = GoogleUtil.getFlow().loadCredential(request.getSession().getId());
		statusGoogle.CREDENTIAL = credential;
		// 要经常调用 credential.refreshToken()，保持token有效
		builder = new Plus.Builder(GoogleUtil.TRANSPORT, GoogleUtil.JSON_FACTORY, credential);
		Plus plus = builder.build();
//		statusGoogle.PLUS = plus;

		Plus.Activities.List listActivities = plus.activities().list("me", "public");
		listActivities.setMaxResults(1L);
		ActivityFeed activityFeed = listActivities.execute();
		List<Activity> activities = activityFeed.getItems();
		if (activities != null && activities.size() != 0) {
			statusGoogle.readOk(activities.get(0).getUpdated().toString());
		} else {
			statusGoogle.readOk("");
		}

		AllStatus.google = statusGoogle;

		response.getWriter().write("ok");
	}

	@Override
	protected void onError(HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse)
			throws ServletException, IOException{

		StringBuilder err = new StringBuilder("There was a problem during authentication: ");

		if (errorResponse != null) {
			err.append(errorResponse.getError());

			if (errorResponse.getErrorUri() != null) {
				err.append(" [").append(errorResponse.getErrorUri()).append("]");
			}

			if (errorResponse.getErrorDescription() != null) {
				err.append(": ").append(errorResponse.getErrorDescription());
			}
		}

		log.info(err.toString());
		resp.sendError(SC_INTERNAL_SERVER_ERROR, GoogleUtil.stripTags(err.toString()));
	}

	@Override
	protected String getRedirectUri(HttpServletRequest request) throws ServletException, IOException{
		return Constant.getAccountInfo("google.oauth_redirect_uri");
	}

	@Override
	protected AuthorizationCodeFlow initializeFlow() throws IOException{
		return GoogleUtil.getFlow();
	}

	@Override
	protected String getUserId(HttpServletRequest request) throws ServletException, IOException{
		return request.getSession(true).getId();
	}

	public static void main(String args[]) throws Exception{
		Plus.Builder builder = new Plus.Builder(GoogleUtil.TRANSPORT, GoogleUtil.JSON_FACTORY, null);
		Plus unauthenticatedPlus = builder.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer(){
			public void initialize(JsonHttpRequest jsonHttpRequest) throws IOException{
				PlusRequest plusRequest = (PlusRequest) jsonHttpRequest;
				plusRequest.setKey(Constant.getAccountInfo("google.google_api_key"));
			}
		}).build();
		
		Plus.Activities.List listActivities = unauthenticatedPlus.activities().list(Constant.getAccountInfo("google.user_id"), "public");
		listActivities.setMaxResults(5L);
		ActivityFeed activityFeed = listActivities.execute();
		List<Activity> activities = activityFeed.getItems();
		for(Activity a : activities){
			System.out.println(a.getObject().getContent());
		}
	}
}
